/*
 * Copyright (c) 2015. For Intelligent Group.
 */

package com.intelligent.ispc.web.controller;

import com.intelligent.ispc.common.dto.JsonPageResponseDto;
import com.intelligent.ispc.common.dto.JsonResponseDto;
import com.intelligent.ispc.common.utils.ApplicationException;
import com.intelligent.ispc.common.utils.ExceptionMessages;
import com.intelligent.ispc.common.web.Servlets;
import com.intelligent.ispc.core.dto.*;
import com.intelligent.ispc.core.service.GRRTestDataService;
import com.intelligent.ispc.core.service.ProjectService;
import com.intelligent.ispc.utils.SystemConfig;
import com.intelligent.ispc.web.utils.PageUtil;
import com.mongodb.util.JSON;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Array;
import java.util.List;
import java.util.Map;

/**
 * Created by Peter.Li on 2015/10/20.
 */
@Controller
@RequestMapping(value = "/project")
public class ProjectController {

    @Autowired
    private ProjectService projectService;

    @Autowired
    private GRRTestDataService grrTestDataService;

    @Autowired
    private SystemConfig systemConfig;

    @RequestMapping(value = "", method = RequestMethod.GET)
    public String nav(Model model, ServletRequest request) {
        Subject subject = SecurityUtils.getSubject();
        if (!subject.isPermitted("project:view")) {
            return "error/noPermission";
        }

        return "project/projectList";
    }

    @RequestMapping(value = "create", method = RequestMethod.GET)
    public String registerForm(Model model) {

        Subject subject = SecurityUtils.getSubject();
        if (!subject.isPermitted("project:create")) {
            return "error/noPermission";
        }

        return "project/newProject";
    }

    @ResponseBody
    @RequestMapping(value = "/list")
    public JsonPageResponseDto list(Model model, ServletRequest request) {
        Subject subject = SecurityUtils.getSubject();
        if (!subject.isPermitted("project:view")) {
            return JsonPageResponseDto.FAILURE().setMessage(ExceptionMessages.EXCEPTION_NO_PERMISSION);
        }

        Map<String, Object> searchParam = Servlets.getParametersStartingWith(request, "search_");

        String sortField = request.getParameter("sortField");

        Page<ProjectDto> page = projectService.searchProject(searchParam, PageUtil.buildPageWithParameters(request, systemConfig.getPageSize(), sortField, Sort.Direction.ASC));
        List<ProjectDto> projects = page.getContent();
        JsonPageResponseDto json = JsonPageResponseDto.SUCCESS().setBody(projects);
        json.setRecordsTotal(page.getTotalElements());
        json.setRecordsFiltered(page.getTotalElements());
        json.setDraw(0);

        return json;
    }

    @ResponseBody
    @RequestMapping(value = "/findAll")
    public JsonPageResponseDto findProject(Model model, ServletRequest request) {
  /*      Subject subject = SecurityUtils.getSubject();
        if (!subject.isPermitted("project:view")) {
            return JsonPageResponseDto.FAILURE().setMessage(ExceptionMessages.EXCEPTION_NO_PERMISSION);
        }*/

        Map<String, Object> searchParam = Servlets.getParametersStartingWith(request, "search_");

        Page<ProjectDto> page = projectService.searchProject(searchParam, null);
        List<ProjectDto> projects = page.getContent();
        JsonPageResponseDto json = JsonPageResponseDto.SUCCESS().setBody(projects);
        json.setRecordsTotal(page.getTotalElements());
        json.setRecordsFiltered(page.getTotalElements());
        json.setDraw(0);

        return json;
    }

    @ResponseBody
    @RequestMapping(value = "/nopermissionList")
    public JsonPageResponseDto listProject(Model model, ServletRequest request) {

        Map<String, Object> searchParam = Servlets.getParametersStartingWith(request, "search_");

        Page<ProjectDto> page = projectService.searchProject(searchParam, null);
        List<ProjectDto> projects = page.getContent();
        JsonPageResponseDto json = JsonPageResponseDto.SUCCESS().setBody(projects);
        json.setRecordsTotal(page.getTotalElements());
        json.setRecordsFiltered(page.getTotalElements());
        json.setDraw(0);

        return json;
    }

    @ResponseBody
    @RequestMapping(value = "/hasPermissionList")
    public JsonPageResponseDto listProjectHasPermissin(Model model, ServletRequest request) {
        Subject subject = SecurityUtils.getSubject();
        if (!subject.isPermitted("project:view")) {
            return JsonPageResponseDto.FAILURE().setMessage(ExceptionMessages.EXCEPTION_NO_PERMISSION);
        }
        Map<String, Object> searchParam = Servlets.getParametersStartingWith(request, "search_");

        Page<ProjectDto> page = projectService.searchProject(searchParam, null);
        List<ProjectDto> projects = page.getContent();
        JsonPageResponseDto json = JsonPageResponseDto.SUCCESS().setBody(projects);
        json.setRecordsTotal(page.getTotalElements());
        json.setRecordsFiltered(page.getTotalElements());
        json.setDraw(0);

        return json;
    }

    @RequestMapping(value = "update/{id}", method = RequestMethod.GET)
    public String edit(@PathVariable("id") String id, Model model) {

        Subject subject = SecurityUtils.getSubject();
        if (!subject.isPermitted("project:edit")) {
            return "error/noPermission";
        }
        ProjectDto projectDto = projectService.findById(id);
        PSGRRDto psgrrDto = projectService.findPSGRRByProject(id);
        model.addAttribute("project", projectDto);
        model.addAttribute("psgrrDto", psgrrDto);

        return "project/projectDetail";
    }

    @ResponseBody
    @RequestMapping(value = "findStatisticAnalysisParameter", method = RequestMethod.POST)
    public JsonResponseDto findStatisticAnalysisParameter(HttpServletRequest request) {

       /* Subject subject = SecurityUtils.getSubject();
        if (!subject.isPermitted("project:view")) {
            return JsonResponseDto.FAILURE().setMessage(ExceptionMessages.EXCEPTION_NO_PERMISSION);
        }*/

        String id = request.getParameter("id");

        StatisticAnalysisParameterDto statisticAnalysisParameterDto = projectService.findStatisticAnalysisParameterByProjectId(id).get(0);
        return JsonResponseDto.SUCCESS().setBody(statisticAnalysisParameterDto);
    }

    @ResponseBody
    @RequestMapping(value = "update", method = RequestMethod.POST)
    public JsonResponseDto update(@ModelAttribute("project") ProjectDto project, Model model) {

        Subject subject = SecurityUtils.getSubject();
        if (!subject.isPermitted("project:edit")) {
            return JsonResponseDto.FAILURE().setMessage(ExceptionMessages.EXCEPTION_NO_PERMISSION);
        }

        try {
            projectService.updateProject(project);
        } catch (ApplicationException ex) {
            return JsonResponseDto.FAILURE().setMessage(ex.getMessage());
        }
        return JsonResponseDto.SUCCESS();
    }

    @ResponseBody
    @RequestMapping(value = "updataDcGroupNumber", method = RequestMethod.POST)
    public JsonResponseDto updateDcGroupNumber(@RequestBody List<StatisticAnalysisParameterDto> list) {

        Subject subject = SecurityUtils.getSubject();
        if (!subject.isPermitted("project:edit")) {
            return JsonResponseDto.FAILURE().setMessage(ExceptionMessages.EXCEPTION_NO_PERMISSION);
        }

        StatisticAnalysisParameterDto statisticAnalysisParameterDto = list.get(0);

        try {
            projectService.updateStatisticAnalysisParameter(statisticAnalysisParameterDto);
        } catch (Exception e) {
            JsonResponseDto.FAILURE().setMessage(e.getMessage());
        }

        return JsonResponseDto.SUCCESS();
    }

    @ResponseBody
    @RequestMapping(value = "updataPSGRR", method = RequestMethod.POST)
    public JsonResponseDto updatePSGRR(@RequestBody List<PSGRRDto> list) {

        Subject subject = SecurityUtils.getSubject();
        if (!subject.isPermitted("project:edit")) {
            return JsonResponseDto.FAILURE().setMessage(ExceptionMessages.EXCEPTION_NO_PERMISSION);
        }

        PSGRRDto psgrrDto = list.get(0);

        try {
            grrTestDataService.updatePSGRR(psgrrDto);
        } catch (Exception e) {
            JsonResponseDto.FAILURE().setMessage(e.getMessage());
        }

        return JsonResponseDto.SUCCESS();
    }

    @ResponseBody
    @RequestMapping(value = "updateCPW", method = RequestMethod.POST)
    public JsonResponseDto updateCPW(@RequestBody List<CPWarningRuleDto> list) {

        Subject subject = SecurityUtils.getSubject();
        if (!subject.isPermitted("project:edit")) {
            return JsonResponseDto.FAILURE().setMessage(ExceptionMessages.EXCEPTION_NO_PERMISSION);
        }

        CPWarningRuleDto cpWarningRuleDto = list.get(0);

        try {
            projectService.updateCPWarningRule(cpWarningRuleDto);
        } catch (Exception e) {
            return JsonResponseDto.FAILURE().setMessage(e.getMessage());
        }
        return JsonResponseDto.SUCCESS();
    }

    @ResponseBody
    @RequestMapping(value = "updateCCW", method = RequestMethod.POST)
    public JsonResponseDto updateCCW(@RequestBody List<ControlChartWarningRuleDto> list) {

        Subject subject = SecurityUtils.getSubject();
        if (!subject.isPermitted("project:edit")) {
            return JsonResponseDto.FAILURE().setMessage(ExceptionMessages.EXCEPTION_NO_PERMISSION);
        }

        ControlChartWarningRuleDto controlChartWarningRuleDto = list.get(0);

        try {
            projectService.updateControlChartWarningRule(controlChartWarningRuleDto);
        } catch (Exception e) {
            return JsonResponseDto.FAILURE().setMessage(e.getMessage());
        }
        return JsonResponseDto.SUCCESS().setBody(controlChartWarningRuleDto);
    }

    @ResponseBody
    @RequestMapping(value = "updatePSA", method = RequestMethod.POST)
    public JsonResponseDto updatePSA(@RequestBody PSAttributeDto psAttributeDto) {

        Subject subject = SecurityUtils.getSubject();
        if (!subject.isPermitted("project:edit")) {
            return JsonResponseDto.FAILURE().setMessage(ExceptionMessages.EXCEPTION_NO_PERMISSION);
        }

//        PSAttributeDto psAttributeDto = list.get(0);

        try {
            projectService.updatePSAttribute(psAttributeDto);
        } catch (Exception e) {
            return JsonResponseDto.FAILURE().setMessage(e.getMessage());
        }
        return JsonResponseDto.SUCCESS().setBody(psAttributeDto);
    }

    @ResponseBody
    @RequestMapping(value = "deletePSA/{id}")
    public JsonResponseDto deletePSA(@PathVariable("id") String id, Model model) {
        Subject subject = SecurityUtils.getSubject();
        if (!subject.isPermitted("project:delete")) {
            return JsonResponseDto.FAILURE().setMessage(ExceptionMessages.EXCEPTION_NO_PERMISSION);
        }
        try {
            projectService.deletePSAttribute(id);
        } catch (Exception e) {
            return JsonResponseDto.FAILURE().setMessage(e.getMessage());
        }

        return JsonResponseDto.SUCCESS();
    }

    @ResponseBody
    @RequestMapping(value = "addPSA/{id}", method = RequestMethod.POST)
    public JsonResponseDto addPSA(@PathVariable("id") String id, String value, Model model) {

        try {
            Subject subject = SecurityUtils.getSubject();
            if (!subject.isPermitted("project:add")) {
                return JsonResponseDto.FAILURE().setMessage(ExceptionMessages.EXCEPTION_NO_PERMISSION);
            }
            PSAttributeDto psAttributeDto = new PSAttributeDto();
            psAttributeDto.setValue(value.trim());
            psAttributeDto.setProject(projectService.findById(id));
            psAttributeDto.setIsDefault(false);
            psAttributeDto.setIsShow(true);
            psAttributeDto.setName(value.trim());
            projectService.addPSAttribute(psAttributeDto);
        } catch (Exception e) {
            return JsonResponseDto.FAILURE().setMessage(e.getMessage());
        }
        return JsonResponseDto.SUCCESS();
    }

    @ResponseBody
    @RequestMapping(value = "cpw")
    public JsonPageResponseDto getCPW(@RequestParam(value = "id") String id, Model model, ServletRequest request) {

       /* Subject subject = SecurityUtils.getSubject();
        if (!subject.isPermitted("project:view")) {
            return JsonPageResponseDto.FAILURE().setMessage(ExceptionMessages.EXCEPTION_NO_PERMISSION);
        }*/
        Page<CPWarningRuleDto> page;
        List<CPWarningRuleDto> cpWarningRuleDtos = null;
        try {
            page = projectService.findCpWarningRulesByProject(id, PageUtil.buildPageWithParameters(request, systemConfig.getPageSize(), "indiceName"));
            cpWarningRuleDtos = page.getContent();

        } catch (ApplicationException ex) {
            return JsonPageResponseDto.FAILURE().setMessage(ex.getMessage());
        }
        JsonPageResponseDto json = JsonPageResponseDto.SUCCESS().setBody(cpWarningRuleDtos);
        json.setRecordsTotal(page.getTotalElements());
        json.setRecordsFiltered(page.getTotalElements());
        json.setDraw(0);
        return json;
    }

    @ResponseBody
    @RequestMapping(value = "ccw")
    public JsonPageResponseDto getCCW(@RequestParam(value = "id") String id, Model model, ServletRequest request) {

      /*  Subject subject = SecurityUtils.getSubject();
        if (!subject.isPermitted("project:view")) {
            return JsonPageResponseDto.FAILURE().setMessage(ExceptionMessages.EXCEPTION_NO_PERMISSION);
        }*/
        Page<ControlChartWarningRuleDto> page;
        List<ControlChartWarningRuleDto> controlChartWarningRuleDtos = null;
        try {

            page = projectService.findControlChartWarningRuleByProject(id, PageUtil.buildPageWithParameters(request, systemConfig.getPageSize(), "code", Sort.Direction.ASC));
            controlChartWarningRuleDtos = page.getContent();

        } catch (ApplicationException ex) {
            return JsonPageResponseDto.FAILURE().setMessage(ex.getMessage());
        }
        JsonPageResponseDto json = JsonPageResponseDto.SUCCESS().setBody(controlChartWarningRuleDtos);
        json.setRecordsTotal(page.getTotalElements());
        json.setRecordsFiltered(page.getTotalElements());
        json.setDraw(0);
        return json;
    }

    @ResponseBody
    @RequestMapping(value = "psa")
    public JsonPageResponseDto getPSA(@RequestParam(value = "id") String id, Model model, ServletRequest request) {

       /* Subject subject = SecurityUtils.getSubject();
        if (!subject.isPermitted("project:view")) {
            return JsonPageResponseDto.FAILURE().setMessage(ExceptionMessages.EXCEPTION_NO_PERMISSION);
        }*/
        Page<PSAttributeDto> page;
        List<PSAttributeDto> psAttributeDtos = null;
        try {
            page = projectService.findPSAttributeByProject(id, null);
            psAttributeDtos = page.getContent();

        } catch (ApplicationException ex) {
            return JsonPageResponseDto.FAILURE().setMessage(ex.getMessage());
        }
        JsonPageResponseDto json = JsonPageResponseDto.SUCCESS().setBody(psAttributeDtos);
        json.setRecordsTotal(page.getTotalElements());
        json.setRecordsFiltered(page.getTotalElements());
        json.setDraw(0);
        return json;
    }

    @ModelAttribute
    public void getProject(@RequestParam(value = "id", defaultValue = "") String id, Model model) {

        if (StringUtils.isNotBlank(id)) {
            model.addAttribute("project", projectService.findById(id));
        }
    }

    @ResponseBody
    @RequestMapping(value = "/findCCWR", method = RequestMethod.POST)
    public JsonResponseDto findDefaultCCWR(Model model) {

//        Subject subject = SecurityUtils.getSubject();
//        if (!subject.isPermitted("project:view")) {
//            return JsonResponseDto.FAILURE().setMessage(ExceptionMessages.EXCEPTION_NO_PERMISSION);
//        }

        List<ControlChartWarningRuleDto> list = projectService.findDefaultControlChartWarningRuleDto();
        JsonResponseDto json = JsonResponseDto.SUCCESS().setBody(list);
        return json;
    }

    @ResponseBody
    @RequestMapping(value = "/findCPWR", method = RequestMethod.POST)
    public JsonResponseDto findDefaultCPWR(Model model) {

       /* Subject subject = SecurityUtils.getSubject();
        if (!subject.isPermitted("project:view")) {
            return JsonResponseDto.FAILURE().setMessage(ExceptionMessages.EXCEPTION_NO_PERMISSION);
        }*/
        List<CPWarningRuleDto> list = projectService.findDefaultCPWarningRuleDto();
        JsonResponseDto json = JsonResponseDto.SUCCESS().setBody(list);
        return json;
    }

    @ResponseBody
    @RequestMapping(value = "/findPSA", method = RequestMethod.POST)
    public JsonResponseDto findDefaultPSA(Model model) {

       /* Subject subject = SecurityUtils.getSubject();
        if (!subject.isPermitted("project:view")) {
            return JsonResponseDto.FAILURE().setMessage(ExceptionMessages.EXCEPTION_NO_PERMISSION);
        }*/
        List<PSAttributeDto> list = projectService.findDefaultPSAttributeDto();
        JsonResponseDto json = JsonResponseDto.SUCCESS().setBody(list);
        return json;
    }

    @ResponseBody
    @RequestMapping(value = "addProject", method = RequestMethod.POST)
    public JsonResponseDto createProject(@RequestBody List<ProjectConfigureParameDto> list) {

        Subject subject = SecurityUtils.getSubject();
        if (!subject.isPermitted("project:create")) {
            return JsonResponseDto.FAILURE().setMessage(ExceptionMessages.EXCEPTION_NO_PERMISSION);
        }

        ProjectConfigureParameDto projectConfigureParameDto = list.get(0);
        try {
            projectService.saveProject(projectConfigureParameDto);

        } catch (ApplicationException ex) {
            return JsonResponseDto.FAILURE().setMessage(ex.getMessage());
        }
        return JsonResponseDto.SUCCESS();
    }

    @ResponseBody
    @RequestMapping(value = "isCode", method = RequestMethod.POST)
    public boolean isCode(HttpServletRequest request) {

//        Subject subject = SecurityUtils.getSubject();
//        if (!subject.isPermitted("project:view")) {
//            return JsonResponseDto.FAILURE().setMessage(ExceptionMessages.EXCEPTION_NO_PERMISSION);
//        }

        String code = request.getParameter("projectCode");
        try {
                projectService.isCode(code);

        } catch (ApplicationException ex) {
            return false;
        }
        return true;
    }


    @ResponseBody
    @RequestMapping(value = "isName", method = RequestMethod.POST)
    public boolean isName(HttpServletRequest request) {

//        Subject subject = SecurityUtils.getSubject();
//        if (!subject.isPermitted("project:view")) {
//            return JsonResponseDto.FAILURE().setMessage(ExceptionMessages.EXCEPTION_NO_PERMISSION);
//        }

        String name = request.getParameter("projectName");

        try {
                projectService.isName(name);

        } catch (ApplicationException ex) {
            return false;
        }
        return true;
    }

    @ResponseBody
    @RequestMapping(value = "checkNameOrCode", method = RequestMethod.POST)
    public boolean checkNameOrCode(HttpServletRequest request) {
//        Subject subject = SecurityUtils.getSubject();
//        if (!subject.isPermitted("project:view")) {
//            return JsonResponseDto.FAILURE().setMessage(ExceptionMessages.EXCEPTION_NO_PERMISSION);
//        }
        Long id = Long.valueOf(request.getParameter("projectId"));
        String name = request.getParameter("projectName");
        String code = request.getParameter("projectCode");

        try {
            projectService.checkNameOrCode(id, name, code);
        } catch (ApplicationException ex) {
            return false;
        }
        return true;
    }
}
